using B.S.XZYData.Api.Wrter.Application.Command.WorkTask;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;

namespace B.S.XZYData.Api.Wrter.Application.Handler.WorkTask
{
    /// <summary>
    /// 批量删除任务处理器
    /// </summary>
    public class BatchDeleteWorkTaskHandler : IRequestHandler<BatchDeleteWorkTaskCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Domain.ZSHH.Task> _taskRepo;
        private readonly ILogger<BatchDeleteWorkTaskHandler> _logger;

        public BatchDeleteWorkTaskHandler(
            IBaseRepository<Domain.ZSHH.Task> taskRepo,
            ILogger<BatchDeleteWorkTaskHandler> logger)
        {
            _taskRepo = taskRepo;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(BatchDeleteWorkTaskCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            try
            {
                if (request.Ids == null || !request.Ids.Any())
                {
                    res.Msg = "请选择要删除的任务";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                var successCount = 0;
                var failCount = 0;

                foreach (var id in request.Ids)
                {
                    try
                    {
                        var task = await _taskRepo.GetValue(id);
                        if (task != null && !task.IsDeleted)
                        {
                            task.IsDeleted = true;
                            task.Updator = request.Deleter;
                            task.UpdatorDate = DateTime.Now;

                            var result = await _taskRepo.UpdateAsync(task);
                            if (result > 0)
                            {
                                successCount++;
                            }
                            else
                            {
                                failCount++;
                            }
                        }
                        else
                        {
                            failCount++;
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"删除任务ID {id} 时发生异常：{ex.Message}");
                        failCount++;
                    }
                }

                res.Data = successCount;
                res.Code = ApiEnum.Success;
                res.Msg = $"批量删除任务完成，成功：{successCount}，失败：{failCount}";

                _logger.LogInformation($"批量删除任务完成，成功：{successCount}，失败：{failCount}");
                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                _logger.LogError($"批量删除任务异常：{ex.Message}");
                res.Msg = "批量删除任务异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }
    }
} 